import { contextMenu } from './context-menu-config';
import { cloneDeep } from 'lodash-es';
import { RowNode } from '@farris/ui-treetable';
import { ContextMenuManager } from '../../../../service/context-menu.manager';
import { ControlContextMenuItem } from '../../../../entity/control-context-menu';
import { FarrisDesignBaseComponent } from '@farris/designer-element';
import { MessagerService } from '@farris/ui-messager';
import { BsModalService } from '@farris/ui-modal';
import { ComponentFactoryResolver } from '@angular/core';
import { ListFilterBuilderService } from './filter-builder';
import { DgControl } from '../../../../utils/dg-control';
import { QuerySchemePresetFieldsEditorComponent } from '../../queryScheme/property/editor/query-scheme-preset-fields-editor/query-scheme-preset-fields-editor.component';
import { QuerySchemeBuilderService } from '../../queryScheme/context-menu/query-scheme-builder';
import { QuerySchemeFieldsEditorComponent } from '../../queryScheme/property/editor/query-scheme-fields-editor/query-scheme-fields-editor.component';

const CHANGE_TO_QUERYSCHEME_COMMAND = 'changeToQueryScheme';

export class ListFilterContextMenuManager extends ContextMenuManager {

    private msgService: MessagerService;
    private modalService: BsModalService;
    private resolver: ComponentFactoryResolver;

    /** 筛选条外层容器Id */
    listFilterContainerId: string;

    constructor(cmp: FarrisDesignBaseComponent, rowNode: RowNode) {
        super(cmp, rowNode);

        this.msgService = this.injector.get(MessagerService);
        this.resolver = this.injector.get(ComponentFactoryResolver);
        this.modalService = this.injector.get(BsModalService);

    }
    /**
     * 过滤、修改控件树右键菜单
     */
    setContextMenuConfig() {
        let menuConfig = cloneDeep(contextMenu) as ControlContextMenuItem[];

        menuConfig = this.assembleChangeToQuerySchemeMenu(menuConfig, this.cmpInstance.viewModelId, this.cmpInstance.id);
        // menuConfig = this.assembleRemoveListFilterMenu(menuConfig, this.cmpInstance.viewModelId, this.cmpInstance.id);


        // 配置菜单点击事件
        this.addContextMenuHandle(menuConfig);

        return menuConfig || [];
    }

    /**
     * 点击控件树右键菜单
     */
    contextMenuClicked(e: { data: RowNode, menu: ControlContextMenuItem }) {

        const menu = e.menu;
        switch (menu.id) {
            case 'changeToQueryScheme': {
                this.openQuerySchemeModal(this.cmpInstance.viewModelId);
                break;
            }
            case 'removeListFilter': {
                this.removeListFilter(this.cmpInstance.viewModelId, this.cmpInstance.id);
                break;
            }
            default: {
                this.notifyService.warning('暂不支持');
            }
        }

    }



    assembleChangeToQuerySchemeMenu(menuConfig: ControlContextMenuItem[], viewModelId: string, filterId: string) {
        const changeToQuerySchemeMenu = menuConfig.find(menu => menu.id === CHANGE_TO_QUERYSCHEME_COMMAND);
        if (!changeToQuerySchemeMenu) {
            return menuConfig;
        }

        // 根组件下的筛选条，不能切换为筛选方案---header组件下的ListFilter(前置任务)，不能切换为筛选方案
        if (viewModelId === 'root-viewmodel') {
            menuConfig = menuConfig.filter(menu => menu.id !== CHANGE_TO_QUERYSCHEME_COMMAND);
            return menuConfig;
        }
        // 当前模板若不能启用筛选方案，则移除菜单
        if (!this.checkCanEnableQueryScheme()) {
            menuConfig = menuConfig.filter(menu => menu.id !== CHANGE_TO_QUERYSCHEME_COMMAND);
            return menuConfig;
        }

        // 若当前表单已有筛选方案，则移除菜单
        const rootComponent = this.domService.getComponentById('root-component');
        const querySchemeNode = this.domService.selectNode(rootComponent, item => item.type === DgControl.QueryScheme.type);
        if (querySchemeNode) {
            menuConfig = menuConfig.filter(menu => menu.id !== CHANGE_TO_QUERYSCHEME_COMMAND);
            return menuConfig;
        }

        // 筛选条外层没有模板预置的容器，则不支持切换筛选方案
        const gridComponent = this.domService.getComponentByVMId(viewModelId);
        const listContainerNode = this.domService.getControlParentById(gridComponent, filterId);
        if (listContainerNode.type !== DgControl.ContentContainer.type || !listContainerNode.appearance ||
            !listContainerNode.appearance.class || !listContainerNode.appearance.class.includes('f-filter-container')) {

            // console.log('未检测到筛选条容器');
            menuConfig = menuConfig.filter(menu => menu.id !== CHANGE_TO_QUERYSCHEME_COMMAND);
            return menuConfig;
        }

        this.listFilterContainerId = listContainerNode.id;
        return menuConfig;
    }

    openQuerySchemeModal(viewModelId: string) {

        this.msgService.question('确定切换为筛选方案？', () => {

            const compFactory = this.resolver.resolveComponentFactory(QuerySchemeFieldsEditorComponent);
            const compRef = compFactory.create(this.injector);

            const modalConfig = {
                title: '筛选方案字段编辑器',
                width: 950,
                height: 500,
                showButtons: true,
                showMaxButton: true,
                buttons: compRef.instance.modalFooter
            };

            compRef.instance.value = [];
            compRef.instance.editorParams = {
                viewModelId,
                presetFieldConfigs: []
            };
            compRef.instance.showPropertyPanel = false;
            const modalPanel = this.modalService.show(compRef, modalConfig);
            compRef.instance.closeModal.subscribe(() => {
                modalPanel.close();
            });
            compRef.instance.submitModal.subscribe((data) => {
                if (data && data.value) {
                    this.openQuerySchemePresetModal(data.value, viewModelId);
                }
                modalPanel.close();
            });

        });

    }
    /**
     * 弹出筛选方案预置字段配置编辑器
     */
    private openQuerySchemePresetModal(fieldConfigs: any[], viewModelId: string) {
        const compFactory = this.resolver.resolveComponentFactory(QuerySchemePresetFieldsEditorComponent);
        const compRef = compFactory.create(this.injector);

        const modalConfig = {
            title: '筛选方案预置字段编辑器',
            width: 950,
            height: 500,
            showButtons: true,
            showMaxButton: true,
            buttons: compRef.instance.modalFooter
        };

        compRef.instance.value = [];
        compRef.instance.editorParams = {
            fieldConfigs
        };
        const modalPanel = this.modalService.show(compRef, modalConfig);
        compRef.instance.closeModal.subscribe(() => {
            modalPanel.close();
        });
        compRef.instance.submitModal.subscribe((data) => {
            if (data && data.value) {


                const filterBuilerService = new ListFilterBuilderService(this.injector);
                const querySchemeBuilerService = new QuerySchemeBuilderService(this.injector);
                // 1、创建筛选方案
                querySchemeBuilerService.createQuerySchemeInDocument(fieldConfigs, data.value);

                // 2、移除筛选条
                filterBuilerService.removeListFilterInDocument(viewModelId);

                // 刷新表单并隐藏属性面板
                this.cmpInstance.emit('clearPropertyPanel');
                this.refreshFormService.refreshFormDesigner.next();

                this.notifyService.success('启用成功');
            }
            modalPanel.close();
        });

    }

    /**
     * 校验是否允许启用筛选方案：根据模板schema中是否包含筛选方案配置来判断
     */
    private checkCanEnableQueryScheme() {
        const templateOutlineSchema = this.domService.templateOutlineSchema || [];
        const querySchemeConfig = templateOutlineSchema.find(schema => schema.queryScheme && schema.queryScheme.canEnable);

        return !!querySchemeConfig;
    }

    /**
     * 若筛选条作为前置任务使用，则需求菜单的中文名称
     * @param menuConfig 菜单配置
     * @param viewModelId 所属视图模型id
     * @param filterId 筛选条id
     */
    // private assembleRemoveListFilterMenu(menuConfig: ControlContextMenuItem[], viewModelId: string, filterId: string) {
    //     const removeListFilterMenu = menuConfig.find(m => m.id === 'removeListFilter');
    //     if (!removeListFilterMenu) {
    //         return menuConfig;
    //     }
    //     const component = this.domService.getComponentByVMId(viewModelId);
    //     const listContainerNode = this.domService.getControlParentById(component, filterId);
    //     const listContainerParentNode = this.domService.getControlParentById(component, listContainerNode.id);

    //     const listContainerParentNodeClass = listContainerParentNode && listContainerParentNode.appearance && listContainerParentNode.appearance.class || '';
    //     if (listContainerParentNodeClass.includes('f-page-header-base')) {
    //         removeListFilterMenu.title = '移除前置任务';
    //     }
    //     return menuConfig;
    // }

    /**
     * 移除筛选条
     * @param viewModelId 所属视图模型id
     * @param filterId 筛选条id
     */
    private removeListFilter(viewModelId: string, filterId: string) {

        this.msgService.question('确定移除筛选条？', () => {
            const gridComponent = this.domService.getComponentByVMId(viewModelId);
            const listContainerNode = this.domService.getControlParentById(gridComponent, filterId);

            if (listContainerNode.type !== DgControl.ContentContainer.type || !listContainerNode.appearance ||
                !listContainerNode.appearance.class || !listContainerNode.appearance.class.includes('f-filter-container')) {

                listContainerNode.contents = listContainerNode.contents.filter(c => c.id !== filterId);
            } else {
                const listContainerParentNode = this.domService.getControlParentById(gridComponent, listContainerNode.id);

                listContainerParentNode.contents = listContainerParentNode.contents.filter(c => c.id !== listContainerNode.id);
            }
            this.cmpInstance.emit('clearPropertyPanel');
            this.refreshFormService.refreshFormDesigner.next();
        });

    }
}

